<?php

namespace apiend\controllers;

use Yii;
use apiend\components\Controller;
use common\logics\SmsCaptchaForm;
use common\models\user\UserMeta;

/**
 * 短信相关接口
 * Site controller
 */
class SmsController extends Controller {

    /**
     * Declares the allowed HTTP verbs.
     * Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
     * @return array the allowed HTTP verbs.
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'actions' => ['account', 'account-check'],
                'allow' => true,
                'roles' => ['@'],
            ],
            [
                'allow' => true,
            ],
        ];
    }

    /**
     * Displays homepage.
     * @return mixed
     */
    public function actionCaptcha() {
        $model = new SmsCaptchaForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('请输入发送验证码所需的手机号和范围信息');
        }
        return $model->send();
    }

    /**
     * 解除绑定验证码
     * @return mixed
     */
    public function actionAccount() {
        $user = UserMeta::findOne($this->token->user_id);
        $mobile = $user->decryptMobile(false);
        $model = new SmsCaptchaForm();
        $model->mobile = $mobile;
        $model->scope = SmsCaptchaForm::SCOPE_ACCOUNT;
        return $model->send();
    }

    /**
     * 解除绑定验证码校验
     * @return mixed
     */
    public function actionAccountCheck() {
        $code = Yii::$app->request->post('code');
        $user = UserMeta::findOne($this->token->user_id);
        $mobile = $user->decryptMobile(false);

        $captcha = Yii::$app->cache->get('captcha_' . SmsCaptchaForm::SCOPE_ACCOUNT . '_' . $mobile);
        if ($captcha == false || $captcha !== $code) {
            parent::error('输入短信验证码不正确');
        }
        Yii::$app->cache->delete('captcha_' . SmsCaptchaForm::SCOPE_ACCOUNT . '_' . $mobile);
        return true;
    }

}
